//
//  DHPayViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/6.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHPayViewController.h"
//#import "BCOfflineStatusResp.h"
//#import "BCOfflineRevertResp.h"
//#import "BCOfflinePayResp.h"
#import <BeeCloud/BeeCloud.h>
#import <BeeCloud/BCPayConstant.h>
#import "DHS2_OrderManagerController.h"
#import "DHUserManagerViewController.h"
#import "DHShoppingCartViewController.h"
#import "DHShoppingCartViewController.h"
#import "DHS2_OrderDetailController.h"
#import "DHSubscribeManagerController.h"

@interface DHPayViewController ()<BeeCloudDelegate>

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UILabel *discountsLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property (weak, nonatomic) IBOutlet UIImageView *wechat;
@property (weak, nonatomic) IBOutlet UIImageView *alipay;

@property (strong, nonatomic) NSNumber *price;
@property (strong, nonatomic) NSString *vip_id;
@property (strong, nonatomic) NSString *vip_name;
@property (strong, nonatomic) NSString *preOrderId;

@property (strong, nonatomic) NSString *order_id;
@property (strong, nonatomic) NSString *size_id;

@property (assign, nonatomic) PayChannel channel;

@end

@implementation DHPayViewController

- (instancetype)initWithPrice:(NSNumber *)price andVipID:(NSString *)vip_id andVipName:(NSString *)vipName preOrderId:(NSString *)preOrderId
{
    self = [super init];
    if (self) {
        self.price = price;
        self.vip_id = vip_id;
        self.vip_name = vipName;
        self.order_id = preOrderId;
    }
    return self;
}


- (instancetype)initWithPrice:(NSNumber *)price order_id:(NSString *)order_id size_id:(NSString *)size_id{
    self = [super init];
    if (self) {
        self.price = price;
        self.order_id = order_id;
        self.size_id = size_id;
    }
    return self;
}

- (instancetype)initWithPrice:(NSNumber *)price order_id:(NSString *)order_id{
    self = [super init];
    if (self) {
        self.price = price;
        self.order_id = order_id;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = @"支付";
    
    self.priceLabel.adjustsFontSizeToFitWidth = YES;
    
    self.channel = PayChannelWxApp;
    
    [self setupUI];
    [self actions];
    
    [BeeCloud setBeeCloudDelegate:self];
}

- (void)setupUI{
    self.view.backgroundColor = [UIColor whiteColor];
    self.bottomView.layer.cornerRadius = 2;
    self.bottomView.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.bottomView.layer.shadowRadius = 5;
    self.bottomView.layer.shadowOpacity = 0.5;
    self.bottomView.layer.shadowOffset  = CGSizeMake(0, 0);
    
    self.priceLabel.text = [NSString stringWithFormat:@"￥%.2f",[self.price floatValue]];
}

- (void)actions{
    __weak typeof(self) weakself = self;
    [self.wechat bk_whenTapped:^{
        [weakself.wechat setImage:[UIImage imageNamed:@"pay_selected"]];
        [weakself.alipay setImage:[UIImage imageNamed:@"pay_unselected"]];
        weakself.channel = PayChannelWxApp;
    }];
    [self.alipay bk_whenTapped:^{
        [weakself.wechat setImage:[UIImage imageNamed:@"pay_unselected"]];
        [weakself.alipay setImage:[UIImage imageNamed:@"pay_selected"]];
        weakself.channel = PayChannelAliApp;
    }];
}

- (IBAction)ensureAction:(id)sender {
    NSString *billno = [self genBillNo];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if (self.payType == PayTypeCompensate) {
        [dict setObject:@"COMPENSATE" forKey:@"payment_type"];
        [dict setObject:[Login curLoginUser]._id forKey:@"user_id"];
        [dict setObject:self.order_id forKey:@"compensate_id"];
    }else if (self.payType == PayTypeOrder){
        [dict setObject:@"ORDER" forKey:@"payment_type"];
        [dict setObject:[Login curLoginUser]._id forKey:@"user_id"];
        [dict setObject:self.order_id forKey:@"order_id"];
    }else if (self.payType == PayTypeVip){
        [dict setObject:@"VIP" forKey:@"payment_type"];
        [dict setObject:[GlobalManager shareGlobalManager].user._id forKey:@"user_id"];
        [dict setObject:self.order_id forKey:@"subscription_id"];
    }
    else{
        return;
    }
    
    BCPayReq *payReq = [[BCPayReq alloc] init];
    payReq.channel = self.channel; //支付渠道
    if (self.payType == PayTypeCompensate) {
        payReq.title = [BeeCloud getCurrentMode] ? @"iOS Demo Sandbox" : @"装衣汇衣物损坏赔偿";; //订单标题
    }else if(self.payType == PayTypeOrder){
        payReq.title = [BeeCloud getCurrentMode] ? @"iOS Demo Sandbox" : @"订单支付";; //订单标题
    }else if(self.payType == PayTypeVip){
        payReq.title = [BeeCloud getCurrentMode] ? @"iOS Demo Sandbox" : @"VIP订阅";; //VIP标题
    }
    
    payReq.totalFee = [NSString stringWithFormat:@"%.0f",[self.price floatValue]*100]; //订单价格
    
    if (self.payType == PayTypeCompensate) {
        payReq.billNo = [self genBillNo];
    }else if(self.payType == PayTypeOrder){
        payReq.billNo = self.order_id;
    }else if(self.payType == PayTypeVip){
        payReq.billNo = self.order_id;
    }
    
    payReq.scheme = @"dresshere"; //URL Scheme,在Info.plist中配置;
    payReq.billTimeOut = 300; //订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}

#pragma mark - BeeCloudDelegate
- (void)onBeeCloudResp:(BCBaseResp *)resp{
    switch (resp.type) {
        case BCObjsTypePayResp:
        {
            // 支付请求响应
            BCPayResp *tempResp = (BCPayResp *)resp;
            if (tempResp.resultCode == 0) {
                // 支付成功
                [NSObject showHudTipStr:resp.resultMsg];
                // 刷新vip数据
                if (self.payType == PayTypeOrder) {
                    DHS2_OrderDetailController *vc = [[DHS2_OrderDetailController alloc] init];
                    vc.order_id = self.order_id;
                    [self.navigationController pushViewController:vc animated:YES];
//                    [[DHNetAPIClient shareDHNetAPIClient] request_payment_statusWithParams:@{@"order_id":self.order_id} andBlock:^(id data, NSError *error) {
//                        if (data) {
//
//                        }
//                    }];
//                    for (UIViewController *controller in self.navigationController.viewControllers) {
//                        if ([controller isKindOfClass:[DHS2_OrderManagerController class]]) {
//                            [self.navigationController popToViewController:controller animated:YES];
//                            postN(@"compensate_pay_success");
//                        }else if ([controller isKindOfClass:[DHShoppingCartViewController class]]){
//                            [self.navigationController popToViewController:controller animated:YES];
//                        }
//                    }
                }else if (self.payType == PayTypeVip){
//                    [[DHNetAPIClient shareDHNetAPIClient] request_payment_statusWithParams:@{@"order_id":self.order_id} andBlock:^(id data, NSError *error) {
//                        if (data) {
//
//                        }
//                    }];
                    [[GlobalManager shareGlobalManager] refreshVIPInfoAndBlock:^(id data, NSError *error) {
                        for (UIViewController *controller in self.navigationController.viewControllers) {
                            if ([GlobalManager shareGlobalManager].vip.vip) {
                                if ([controller isKindOfClass:[DHUserManagerViewController class]]) {
                                    [self.navigationController popToViewController:controller animated:YES];
                                }else if ([controller isKindOfClass:[DHShoppingCartViewController class]]){
                                    [self.navigationController popToViewController:controller animated:YES];
                                }
                            }else{
                                [[GlobalManager shareGlobalManager] refreshVIPInfoAndBlock:^(id data, NSError *error) {
                                    for (UIViewController *controller in self.navigationController.viewControllers) {
                                        if ([GlobalManager shareGlobalManager].vip.vip) {
                                            if ([controller isKindOfClass:[DHUserManagerViewController class]]) {
                                                [self.navigationController popToViewController:controller animated:YES];
                                            }else if ([controller isKindOfClass:[DHShoppingCartViewController class]]){
                                                [self.navigationController popToViewController:controller animated:YES];
                                            }
                                        }else{
                                            [[GlobalManager shareGlobalManager] refreshVIPInfoAndBlock:^(id data, NSError *error) {
                                                if ([controller isKindOfClass:[DHUserManagerViewController class]]) {
                                                    [self.navigationController popToViewController:controller animated:YES];
                                                }else if ([controller isKindOfClass:[DHShoppingCartViewController class]]){
                                                    [self.navigationController popToViewController:controller animated:YES];
                                                }
                                            }];
                                        }
                                    }
                                }];
                            }
                        }
                    }];
                }else if (self.payType == PayTypeCompensate){
                    for (UIViewController *controller in self.navigationController.viewControllers) {
                        if ([controller isKindOfClass:[DHSubscribeManagerController class]]) {
                            [self.navigationController popToViewController:controller animated:YES];
                        }
                    }
                }
            } else {
                //支付取消或者支付失败
                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
            [self dismissViewControllerAnimated:NO completion:nil];
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        }
            break;
        case BCObjsTypeQueryBillsResp:
        {
            BCQueryBillsResp *tempResp = (BCQueryBillsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [NSObject showHudTipStr:@"未找到相关订单信息"];
                } else {
                    //                    self.orderList = tempResp;
                    //                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        case BCObjsTypeQueryRefundsResp:
        {
            BCQueryRefundsResp *tempResp = (BCQueryRefundsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [NSObject showHudTipStr:@"未找到相关订单信息"];
                } else {
                    //                    self.orderList = tempResp;
                    //                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
            
        case BCObjsTypeOfflinePayResp:
        {
//            BCOfflinePayResp *tempResp = (BCOfflinePayResp *)resp;
//            if (resp.resultCode == 0) {
//                BCOfflinePayReq *payReq = (BCOfflinePayReq *)tempResp.request;
//                switch (payReq.channel) {
//                    case PayChannelAliOfflineQrcode:
//                    case PayChannelWxNative:
//                    case PayChannelBCNative:
//                    case PayChannelBCAliQrcode:
//                        if (tempResp.codeurl.isValid) {
//                            //                            QRCodeViewController *qrCodeView = [[QRCodeViewController alloc] init];
//                            //                            qrCodeView.resp = tempResp;
//                            //                            qrCodeView.delegate = self;
//                            //                            [self.navigationController pushViewController:qrCodeView animated:YES];
//                        }
//                        break;
//                    case PayChannelAliScan:
//                    case PayChannelWxScan:
//                    case PayChannelBCWxScan:
//                    case PayChannelBCAliScan:
//                    {
//                        BCOfflineStatusReq *req = [[BCOfflineStatusReq alloc] init];
//                        req.channel = payReq.channel;
//                        req.billNo = payReq.billNo;
//                        [BeeCloud sendBCReq:req];
//                    }
//                        break;
//                    default:
//                        break;
//                }
//            } else {
//                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
//            }
        }
            break;
        case BCObjsTypeOfflineBillStatusResp:
        {
//            static int queryTimes = 1;
//            BCOfflineStatusResp *tempResp = (BCOfflineStatusResp *)resp;
//            if (tempResp.resultCode == 0) {
//                if (!tempResp.payResult && queryTimes < 3) {
//                    queryTimes++;
//                    [BeeCloud sendBCReq:tempResp.request];
//                } else {
//                    [NSObject showHudTipStr:tempResp.payResult?@"支付成功":@"支付失败"];
//                    //                BCOfflineRevertReq *req = [[BCOfflineRevertReq alloc] init];
//                    //                req.channel = tempResp.request.channel;
//                    //                req.billno = tempResp.request.billno;
//                    //                [BeeCloud sendBCReq:req];
//                    queryTimes = 1;
//                }
//                
//            } else {
//                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
//            }
        }
            break;
        case BCObjsTypeOfflineRevertResp:
        {
#pragma mark - 线下撤销订单响应事件类型，包含WX_SCAN,ALI_SCAN,ALI_OFFLINE_QRCODE
//            BCOfflineRevertResp *tempResp = (BCOfflineRevertResp *)resp;
//            if (resp.resultCode == 0) {
//                [NSObject showHudTipStr:tempResp.revertStatus?@"撤销成功":@"撤销失败"];
//            } else {
//                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
//            }
        }
            break;
        default:
        {
            if (resp.resultCode == 0) {
                [NSObject showHudTipStr:resp.resultMsg];
            } else {
                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",resp.resultMsg, resp.errDetail]];
            }
        }
            break;
    }
}

#pragma mark - 生成订单号
- (NSString *)genBillNo {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmssSSS"];
    
    NSString *_id = [GlobalManager shareGlobalManager].user._id;
    NSString *str = [NSString stringWithFormat:@"%@%.0f%@",[formatter stringFromDate:[NSDate date]],[self.price floatValue] * 100, [_id substringFromIndex:_id.length - 8 ]];
    return str;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
